package com.lyhengtongwl.zqsnews.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.base.BaseActivity;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.net.Url;
import com.lyhengtongwl.zqsnews.utils.AppConfig;
import com.lyhengtongwl.zqsnews.utils.JpushSetAliasUtils;
import com.lyhengtongwl.zqsnews.utils.NewsToastUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.widget.CenterDialog;

import java.util.HashMap;

import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import retrofit2.Response;

public class NewsLoginActivity extends BaseActivity{
    private String nickName;
    private String headImgUrl;
    private String openId;
    private String sex;
    private String unionid;
    private Dialog dialog;
    @Override
    public void setListen() {
    }

    @Override
    public void setTitleBarColor() {
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_news_login_new;
    }

    @Override
    public void initView() {
        Intent it = getIntent();
        String data = it.getStringExtra("data");
        String msg = it.getStringExtra("msg");
        if (!"".equals(data) && data != null && !"".equals(msg) && msg != null) {
            new CenterDialog(R.layout.item_forbidden, NewsLoginActivity.this).showForBidPrompt(msg, data);
        }

    }

    @Override
    public void initData() {
    }

    @Override
    protected boolean isStatusBarBlack() {
        return true;
    }

    @OnClick({R.id.ll_wc_login, R.id.tv_user, R.id.tv_privacy})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ll_wc_login:
                byWCLogin();
                break;
            case R.id.tv_user://用户协议
                startActivity(new Intent(NewsLoginActivity.this, NewsWebCommonActivity.class).putExtra("url", AppConfig.getInstance(App.getContext()).get("userUrl")));
                break;
            case R.id.tv_privacy://隐私协议
                startActivity(new Intent(NewsLoginActivity.this, NewsWebCommonActivity.class).putExtra("url", AppConfig.getInstance(App.getContext()).get("privacyUrl")));
                break;
        }
    }


    //用户登录

    //微信登录
    private void byWCLogin() {
        dialog = new CenterDialog(R.layout.loading_layout, NewsLoginActivity.this).showLoad("授权登录中...");
        //检测是否安装微信
        Platform wc = ShareSDK.getPlatform(Wechat.NAME);
        if (wc.isClientValid()) {
            wc.removeAccount(true); //移除授权状态和本地缓存，下次授权会重新授权
            wc.SSOSetting(false);  //设置false表示使用SSO授权方式
            wc.setPlatformActionListener(new PlatformActionListener() {
                @Override
                public void onComplete(Platform platform, int i, HashMap<String, Object> res) {
                    String jsonString = JSON.toJSONString(res);
                    JSONObject jsonObject = JSONObject.parseObject(jsonString);
                    //获取资料
                    unionid = jsonObject.getString("unionid");
                    nickName = jsonObject.getString("nickname");
                    headImgUrl = jsonObject.getString("headimgurl");
                    openId = jsonObject.getString("openid");
                    sex = jsonObject.getInteger("sex") + "";
                    SPUtils.put(App.getContext(), "nickName", nickName);
                    //检测是否绑定手机号
                    checkBind(unionid);
                }

                @Override
                public void onError(Platform platform, int i, Throwable throwable) {
                    NewsToastUtils.showToast(App.getContext(), "微信登录失败！");
                }

                @Override
                public void onCancel(Platform platform, int i) {
                    NewsToastUtils.showToast(App.getContext(), "微信登录取消！");
                }
            }); // 设置分享事件回调
            wc.showUser(null);//授权并获取用户信息
        } else {
            NewsToastUtils.showToast(App.getContext(), "微信版本太低或未安装微信！");
        }
    }


    //检测手机号是否绑定
    private void checkBind(String unionId) {
        String url = Url.BaseUrl + "/htLogin/checkBindMobile/" + unionId;
        Task.getApiService().checkBind(url).enqueue(new MyCallback<NewsBaseEntity>(NewsLoginActivity.this) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                if ("1".equals(response.body().getCode())) {
                    String jsonStr = JSONObject.toJSONString(response.body().getData());
                    JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                    boolean isBind = jsonObject.getBoolean("isBind");
                    if (!isBind) {
                        //表示用户不存在 需要去绑定
                        startActivity(new Intent(NewsLoginActivity.this, NewsBindMobileActivity.class)
                                .putExtra("avatar", headImgUrl)
                                .putExtra("nickname", nickName)
                                .putExtra("openid", openId)
                                .putExtra("sex", sex)
                                .putExtra("unionid", unionid));
                        finish();
                    } else {
                        String token = jsonObject.getString("token");
                        Integer userId = jsonObject.getInteger("userId");
                        String redBag = jsonObject.getInteger("redBag") + "";
                        String randomCode = jsonObject.getString("randomCode");
                        String shareCode = jsonObject.getString("shareCode");
                        SPUtils.put(App.getContext(), "redBag", redBag);
                        SPUtils.put(App.getContext(), "token", token);
                        SPUtils.put(App.getContext(), "userId", userId.toString());
                        SPUtils.put(App.getContext(), "random_code", randomCode);
                        SPUtils.put(App.getContext(), "shareCode", shareCode);
                        new JpushSetAliasUtils(NewsLoginActivity.this).setAlias(userId + "");
                        //表示用户存在直接进行登录
                        startActivity(new Intent(NewsLoginActivity.this, MainActivity.class));
                        finish();
                    }
                }
                dialog.dismiss();
            }

            @Override
            protected void onFailure(Throwable t) {
                dialog.dismiss();
            }
        });
    }
}
